<template>

  <el-breadcrumb separator="/">

    <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>

    <el-breadcrumb-item>师资管理</el-breadcrumb-item>

    <el-breadcrumb-item>咨询师管理</el-breadcrumb-item>

  </el-breadcrumb>


  <el-form style="margin-top: 30px;" :inline="true" size="large">
    <el-form-item label="咨询师名称">
      <el-input v-model="formData.name" placeholder="请输入咨询师名称" clearable @clear="refreshPage"
        style="width: 250px;"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getAllComm">搜索</el-button>
      <el-button type="primary" @click="adddate">新增咨询师</el-button>
    </el-form-item>
  </el-form>

  <el-form>
    <el-table :data="visitList" border class="my-table" size="large" @selection-change="handleSelectionChange">
      <el-table-column type="selection" :selectable="selectable" width="55" />
      <el-table-column prop="id" label="ID" align="center"></el-table-column>
      <el-table-column prop="name" label="咨询师名" align="center"></el-table-column>
      <el-table-column prop="consultLevel.name" label="咨询师等级" align="center">
        


      </el-table-column>


      <el-table-column prop="img" label="咨询师头像" align="center" width="150">
        <template v-slot="scope">
          <img :src="`http://localhost:8081/sfzy${scope.row.img}`" alt="头像" class="table-img">
        </template>
      </el-table-column>




      <el-table-column prop="model" label="电话" align="center"></el-table-column>
      <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
      <el-table-column prop="sex" label="性别" align="center"></el-table-column>
      <!-- 证书图片 -->

      <el-table-column prop="book" label="证书图片" align="center" width="150">
        <template v-slot="scope">
          <img :src="`http://localhost:8081/sfzy${scope.row.book}`" alt="图片" class="table-img">
        </template>
      </el-table-column>


      <el-table-column prop="address" label="咨询地址" align="center"></el-table-column>
      <el-table-column prop="intro" label="咨询师简介" align="center"></el-table-column>
      <!-- <el-table-column prop="position" label="咨询师擅长领域">
        <template slot-scope="scope">
          <span v-if="
            scope.row.position &&
            scope.row.position.length
          ">
            {{
              scope.row.position
                .map((item) => item.specialty.name)
                .join(",")
            }}
          </span>
          <span v-else>暂无擅长领域</span>
        </template>
      </el-table-column> -->
      <el-table-column prop="position" label="职位" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-link type="primary" @click="updata(scope.row)">修改</el-link>
          <el-link type="danger" @click="handleDownshelf(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
  </el-form>



<!-- 这个是添加的内容 -->

  <el-dialog v-model="dialogFormVisible" :title="title" width="525" @close="cancel">
    <el-form :model="adddate" class="form1">
      <el-form-item label="咨询师名称" :label-width="formLabelWidth">
        <el-input v-model="visitData.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="咨询师等级" label-width="120px">

        <el-select v-model="visitData.levelId" filterable placeholder="请选择咨询师等级">

          <el-option v-for="item in classList" :key="item.id" :label="item.name" :value="item.id">

          </el-option>

        </el-select>

      </el-form-item>



      <el-form-item label="头像" :label-width="formLabelWidth">
        <el-upload drag class="avatar-uploader" method="post" action="http://localhost:8081/sfzy/upload"
          :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="form.imgUrl" :src="`${form.imgUrl}`" class="avatar" />
          <div v-else>
            <el-icon class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="电话" :label-width="formLabelWidth">
        <el-input v-model="visitData.model" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱" :label-width="formLabelWidth">
        <el-input v-model="visitData.email" autocomplete="off" />
      </el-form-item>
      <el-form-item label="性别" :label-width="formLabelWidth">
        <el-input v-model="visitData.sex" autocomplete="off" />
      </el-form-item>

      <el-form-item label="证书头像" :label-width="formLabelWidth">
        <el-upload drag class="avatar-uploader" method="post" action="http://localhost:8081/sfzy/upload"
          :show-file-list="false" :on-success="handleAvatarSuccess1" :before-upload="beforeAvatarUpload">
          <img v-if="form.imgUrl1" :src="`${form.imgUrl1}`" class="avatar" />
          <div v-else>
            <el-icon class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="地址" :label-width="formLabelWidth">
        <el-input v-model="visitData.address" autocomplete="off" />
      </el-form-item>

      <el-form-item label="简介" :label-width="formLabelWidth">
        <el-input v-model="visitData.intro" autocomplete="off" />
      </el-form-item>

      <el-form-item label="职位" label-width="120px">

        <el-select v-model="visitData.position" filterable placeholder="">

          <el-option v-for="item in classList1" :key="item.id" :label="item.name" :value="item.id">

          </el-option>

        </el-select>

      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <el-row>
    <el-pagination :page-sizes="[4, 10, 30, 40]" :size="size" :disabled="disabled" :background="background"
      :default-page-size="4" layout="total, sizes, prev, pager, next, jumper" :total="total"
      @size-change="handleSizeChange" @current-change="pageNumChange" />
  </el-row>
</template>

<script setup>
//获取城市内容

//icon图标
import { Search, Refresh, Edit, CloseBold, Plus, Share, ArrowRight } from '@element-plus/icons-vue'
//信息提示
import { ElForm, ElMessage, ElMessageBox, uploadProps } from 'element-plus';
//getCurrentInstance获取全局对象，用于获取axios属性
//onMounted页面加载后开始挂载执行
//watchEffect属性监听器，daterange响应后开始执行函数，这里用于获取开始时间和结束时间
import { getCurrentInstance, onMounted, ref, watchEffect, onBeforeUnmount } from 'vue';
//接收全局对象
const CurrentInstance = getCurrentInstance()
//初始化添加弹框，使其不显示
const dialogFormVisible = ref(false)
//添加弹出框左边距
const formLabelWidth = '140px'
//获取全局对象挂载的naxios赋值给$http来代替naxios
const { $http } = CurrentInstance.appContext.config.globalProperties
//弹出框的标题
const title = ref("")
//代表active样式
const i = ref("")
//默认动态页码为0
const total = ref(0)


const classList=ref([])
const classList1=ref([])
//动态方法，默认弹出框为add
const operationType = ref('add');
let form = ref({
  imgUrl: '',
  imgUrl1:''
})
const imageUrl = ref('')
// 图片上传成功的钩子  
const handleAvatarSuccess = (response, uploadFile) => {
  // 保存相对路径到相关数据对象，以便传给后端
  const relativeImagePath = response.data;
  // 拼接完整的图片路径在弹出框中显示
  const fullImagePath = `http://localhost:8081/sfzy${response.data}`;
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
  form.value.imgUrl = fullImagePath

  //传回数据库的路径
  visitData.value.img = relativeImagePath;
};
const handleAvatarSuccess1 = (response, uploadFile) => {
  // 保存相对路径到相关数据对象，以便传给后端
  const relativeImagePath = response.data;
  // 拼接完整的图片路径在弹出框中显示
  const fullImagePath = `http://localhost:8081/sfzy${response.data}`;
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
  form.value.imgUrl1 = fullImagePath

  //传回数据库的路径
  visitData.value.book = relativeImagePath;
};
onBeforeUnmount(() => {
  URL.revokeObjectURL(imageUrl.value);
});
//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload = (rawFile) => {
  const allowedFormats = ['image/jpeg', 'image/png']; // 允许的文件格式
  if (!allowedFormats.includes(rawFile.type)) {
    this.$message.error('文件格式必须是 JPG 或 PNG！');
    return false;
  }
  else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
//定义formData来接收访问地址的数据
const formData = ref({
  name: "",
  pageNum: 1,// 页码
  pageSize: 5, // 每页展示条数
  ids: []//多选id

})
//定义的表格数据来存放访问地址中的数据
let visitList = ref([

])

let visitData = ref({
  address: "",
  book: "",
  del: "",
  email: "",
  id: "",
  img: "",
  intro: "",
  // levelId: "",
  model: "",
  name: "",
  position: "",
  sex: "",
})
//监听函数，if else是为了防止访问空时报错，同时获取页面的开始时间和结束时间
watchEffect(function () {

})
//点击搜索的清除组件，刷新页面
function refreshPage() {
  getAllComm();
  multiple();
}
//生命周期中挂载到页面加载之后开始执行
onMounted(() => {
  getAllComm()
  multiple();
  multiple1();
})
//获取点击的分页页码并执行搜索功能
function pageNumChange(num) {
  formData.value.pageNum = num;
  getAllComm()
}
function handleSizeChange(size) {
  formData.value.pageSize = size;
  getAllComm()
}
//搜索功能，将formData的定义初始属性传给访问地址，并传回来地址中的表格数据和各个属性
function getAllComm() {
  $http({
    method: "get",
    url: "http://localhost:8081/sfzy/consult/page",
    params: formData.value
  }).then(res => {
    visitList.value = res.data.data.list;
    total.value = res.data.data.total;
  })
}
// 新增分类函数
function addNewCategory() {
  $http({
    method: "post",
    url: "http://localhost:8081/sfzy/consult",
    data: visitData.value
  }).then(res => {
    if (res.data.code === 200) {
      ElMessage.success("添加成功！");
    } else {
      ElMessage.error("添加失败");
    }
    dialogFormVisible.value = false;
    getAllComm();
    cancel();
  });
}

function multiple(){
  $http({
    method:"get",
    url:"http://localhost:8081/sfzy/consultLevel"
  }).then(res=>{
    classList.value=res.data.data
  })
}
function multiple1(){
  $http({
    method:"get",
    url:"http://localhost:8081/sfzy/specialty"
  }).then(res=>{
    classList1.value=res.data.data
  })
}



// 使添加框显示（新增分类）
function adddate() {
  dialogFormVisible.value = true;
  title.value = "新增咨询师";
  operationType.value = 'add';
  // 初始化相关数据（可根据实际需求补充更多初始化操作）
  visitData.value = {
    address: "",
    book: "",
    del: null,
    email: "",
    id: "",
    img: "",
    intro: "",
    levelId: "",
    model: "",
    name: "",
    position: "",
    sex: "",
  };
}
// 修改分类函数
function updateCategory(val) {
  $http({
    method: "put",
    url: "http://localhost:8081/sfzy/consult",
    data: val
  }).then(res => {
    if (res.data.code === 200) {
      ElMessage.success("修改成功！");
    } else {
      ElMessage.error("修改失败");
    }
    dialogFormVisible.value = false;
    getAllComm();
    cancel();
  });
}
// 点击修改链接弹出修改框并执行修改操作
function updata(val) {
  dialogFormVisible.value = true;
  title.value = "修改分类";
  visitData.value = val;
  operationType.value = 'modify';
  form.value.imgUrl = `http://localhost:8081/sfzy${val.img}`
  form.value.imgUrl1 = `http://localhost:8081/sfzy${val.book}`
}
// 统一提交函数，根据操作类型调用相应函数
function handleSubmit() {
  if (operationType.value === 'add') {
    addNewCategory();
  } else if (operationType.value === 'modify') {
    updateCategory(visitData.value);
  }
}
//删除功能
function handleDownshelf(val) {
  ElMessageBox.confirm(
    '是否确认删除数据?',
    '删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const { id } = val;
      $http({
        method: "delete",
        url: `http://localhost:8081/sfzy/consult/${id}`,
        data: {}
      }).then(res => {
        if (res.data.code === 200) {
          ElMessage.success("删除成功！");
        } else {
          ElMessage.error("删除失败");
        }
        getAllComm();
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除操作',
      })
    })
}
//批量删除
const selectable = (row) => ![].includes(row.id)
const handleSelectionChange = (val) => {
  formData.value.ids = val.map(item => item.id);
}
function removeBatch() {
  ElMessageBox.confirm(
    '是否确认删除小区数据?',
    '删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const idsArray = formData.value.ids;
      // 将数组idsArray中的元素拼接成字符串形式，用逗号分隔
      const idsStr = idsArray.join(',');

      $http({
        method: "delete",
        url: `http://localhost:8081/sfzy/consult?ids=${idsStr}`,
        data: {}
      }).then(res => {
        if (res.data.code === 200) {
          ElMessage.success("删除成功！");
          // 判断当前页是否还有数据，如果没有则将页码减1
          if (visitList.value.length === 0 && formData.value.pageNum > 1) {
            formData.value.pageNum--;
          }
          // 清理ids参数
          formData.value.ids = [];
        } else {
          ElMessage.error("删除失败");
        }
        getAllComm();
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除操作',
      })
    })
}
//折扣价和原价判定
function validateNumber(field) {
  const value = visitData.value[field];
  // 使用正则表达式匹配非数字字符
  const nonNumberRegex = /\D/g;
  const newVal = value.replace(nonNumberRegex, '');
  if (newVal !== value) {
    visitData.value[field] = newVal;
    ElMessage.warning('请输入数字');
  }
}
//重置添加输入框内容
function cancel() {
  dialogFormVisible.value = false;
  imageUrl.value = ""
  form.value = {
    imgUrl: ''
  }
  visitData.value = {
    address: "",
    book: "",
    del: null,
    email: "",
    id: "",
    img: "",
    intro: "",
    levelId: "",
    model: "",
    name: "",
    position: "",
    sex: "",
  }
  getAllComm()
}

</script>

<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.el-link {
  padding: 0 5px;
}

.el-form {
  width: 1420px;
}

.el-input {
  width: 300px;
}

.form1 {
  width: 100%;
}

.el-pagination {
  margin-top: 25px;
}

.coordinates {
  margin-left: 10px;
}

.my-table :deep(th) {
  background-color: #1890ff;
  color: #ffffff;
  text-align: center;
}

.mendian {
  margin-bottom: 15px;
}

.active {
  color: green;
}

.c1 {
  color: #1890ff;
  cursor: pointer;
}

.c2 {
  color: red;
  cursor: pointer;
}

.table-img {
  width: 100px;
  /* 根据需要调整图片宽度 */
  height: 100px;
  /* 根据需要调整图片高度 */
  object-fit: cover;
  /* 控制图片如何填充容器，cover会保持图片比例并填满容器 */
}

.avatar-uploader .avatar {
  padding: none;
  margin: 0 30px 0;
  width: 100px;
  height: 100px;
  display: block;
}

.el-icon.avatar-uploader-icon {
  padding: 0 30px 0;
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
}
</style>